package com.platform.api;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.platform.util.CommonUtil;
import com.qiniu.util.StringUtils;
import com.platform.annotation.LoginUser;
import com.platform.dto.CouponInfoVo;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

import static com.platform.config.Constants.FREIGHT_PRICE;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/cart")
public class ApiCartController extends ApiBaseAction {
    @Autowired
    private ApiCartService cartService;
    @Autowired
    private ApiGoodsService goodsService;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiGoodsSpecificationService goodsSpecificationService;
    @Autowired
    private ApiAddressService addressService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiSysMacroService macroService;
    @Autowired
    private ApiInvoiceService apiInvoiceService;

    /**
     * 获取购物车中的数据
     */
    @RequestMapping("getCart")
    public Object getCart(@LoginUser UserVo loginUser) {

        Map<String, Object> resultObj = new HashMap<>();

        //查询列表数据
        Map<String, Object> param = new HashMap<>();
        param.put("user_id", loginUser.getUserId());
        List<CartVo> cartList = cartService.queryList(param);

        //获取购物车统计信息
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();

            //todo 处理商品自身优惠
            Integer goodsId = cartItem.getGoods_id();
            GoodsVo goodsVo = goodsService.queryObject(goodsId);
            if (goodsVo == null) {
                return toResponsFail(cartItem.getProduct_name() + "已下架");
            }
            Integer isFullReduction = goodsVo.getIs_full_reduction();//是否满减1-是；0-否
            Integer isRebate = goodsVo.getIs_rebate();//是否折扣商品：1-是；0-否
            Integer isSecondHalfPrice = goodsVo.getIs_second_half_price();//是否第二份半价：1-是；0-否

            //情况1：满减
            BigDecimal multiply = cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber()));

            if (isFullReduction == 1 && isRebate == 0 && isSecondHalfPrice == 0) {
                if (multiply.compareTo(goodsVo.getReduction_demand_price()) >= 0) {
                    multiply = multiply.subtract(goodsVo.getReduction_price());
                }
                goodsAmount = goodsAmount.add(multiply);

            }
            //情况2：折扣商品：按照原价计算
            if (isFullReduction == 0 && isRebate == 1 && isSecondHalfPrice == 0) {
                goodsAmount = goodsAmount.add(multiply);
            }

            //情况3：第二份半价
            if (isFullReduction == 0 && isRebate == 0 && isSecondHalfPrice == 1) {
                goodsAmount = goodsAmount.add(CommonUtil.getTotalPrice(cartItem.getRetail_price(), cartItem.getNumber()));
            }

            //情况4：没有优惠
            if (isFullReduction == 0 && isRebate == 0 && isSecondHalfPrice == 0) {
                goodsAmount = goodsAmount.add(multiply);
            }

            //购物车中选中的商品
            if (null != cartItem.getChecked() && 1 == cartItem.getChecked()) {

                checkedGoodsCount += cartItem.getNumber();
                //情况1：满减
                if (isFullReduction == 1 && isRebate == 0 && isSecondHalfPrice == 0) {
                    if (multiply.compareTo(goodsVo.getReduction_demand_price()) >= 0) {
                        multiply = multiply.subtract(goodsVo.getReduction_price());
                    }
                    checkedGoodsAmount = checkedGoodsAmount.add(multiply);

                }
                //情况2：折扣商品：按照原价计算
                if (isFullReduction == 0 && isRebate == 1 && isSecondHalfPrice == 0) {
                    checkedGoodsAmount = checkedGoodsAmount.add(multiply);
                }

                //情况3：第二份半价
                if (isFullReduction == 0 && isRebate == 0 && isSecondHalfPrice == 1) {
                    checkedGoodsAmount = checkedGoodsAmount.add(CommonUtil.getTotalPrice(cartItem.getRetail_price(), cartItem.getNumber()));
                }

                //情况4：没有优惠
                if (isFullReduction == 0 && isRebate == 0 && isSecondHalfPrice == 0) {
                    checkedGoodsAmount = checkedGoodsAmount.add(multiply);
                }
            }
        }
        // 获取优惠信息提示
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("enabled", true);
//        Integer[] send_types = new Integer[]{0, 7};
        Integer[] send_types = new Integer[]{7};
        couponParam.put("send_types", send_types);
        List<CouponInfoVo> couponInfoList = new ArrayList<>();
        List<CouponVo> couponVos = apiCouponService.queryList(couponParam);
        if (null != couponVos && couponVos.size() > 0) {
            CouponInfoVo fullCutVo = new CouponInfoVo();
            BigDecimal fullCutDec = new BigDecimal(0);
            BigDecimal minAmount = new BigDecimal(100000);
            for (CouponVo couponVo : couponVos) {
                //优惠券最小商品金额-勾选了购物车中商品的总金额（保留两位小数）
                BigDecimal difDec = couponVo.getMin_goods_amount().subtract(checkedGoodsAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                //Send_type 0：按订单发放 1：按用户发放 2:商品转发送券 3：按商品发放 4:新用户注册 5：线下发放 6评价好评红包（固定或随机红包） 7包邮
                //如果优惠券类型是'按订单发放'，并且上述difDec大于0，并且minAmount大于优惠券最小商品金额
                if (couponVo.getSend_type() == 0 && difDec.doubleValue() > 0.0 && minAmount.compareTo(couponVo.getMin_goods_amount()) > 0) {
                    fullCutDec = couponVo.getType_money();//满减金额
                    minAmount = couponVo.getMin_goods_amount();//最小商品金额
                    fullCutVo.setType(1);// 是否凑单 0否 1是
                    fullCutVo.setMsg(couponVo.getName() + "，还差" + difDec + "元");
                }
                //如果优惠券类型是'按订单发放'，并且上述difDec小于0，并且满减金额小于优惠券的优惠金额
                else if (couponVo.getSend_type() == 0 && difDec.doubleValue() < 0.0 && fullCutDec.compareTo(couponVo.getType_money()) < 0) {
                    fullCutDec = couponVo.getType_money();
                    fullCutVo.setType(0);
                    fullCutVo.setMsg("可使用满减券" + couponVo.getName());
                }
                //包邮
                if (couponVo.getSend_type() == 7 && difDec.doubleValue() > 0.0) {
                    CouponInfoVo cpVo = new CouponInfoVo();
                    cpVo.setMsg("满￥" + couponVo.getMin_goods_amount() + "元免配送费，还差" + difDec + "元");
                    cpVo.setType(1);
                    couponInfoList.add(cpVo);
                } else if (couponVo.getSend_type() == 7) {
                    CouponInfoVo cpVo = new CouponInfoVo();
                    cpVo.setMsg("满￥" + couponVo.getMin_goods_amount() + "元免配送费");
                    couponInfoList.add(cpVo);
                }
            }
            if (!StringUtils.isNullOrEmpty(fullCutVo.getMsg())) {
                couponInfoList.add(fullCutVo);
            }
        }
        resultObj.put("couponInfoList", couponInfoList);
        resultObj.put("cartList", cartList);
        //
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);
        //
        resultObj.put("cartTotal", cartTotal);
        return resultObj;
    }

    /**
     * 获取购物车信息，所有对购物车的增删改操作，都要重新返回购物车的信息
     */
    @RequestMapping("index")
    public Object index(@LoginUser UserVo loginUser) {
        return toResponsSuccess(getCart(loginUser));
    }

    private String[] getSpecificationIdsArray(String ids) {
        String[] idsArray = null;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(ids)) {
            String[] tempArray = ids.split("_");
            if (null != tempArray && tempArray.length > 0) {
                idsArray = tempArray;
            }
        }
        return idsArray;
    }

    /**
     * 添加商品到购物车
     *
     * @param loginUser 判断登录状态
     * @param goodsId   商品id
     * @param productId 产品id
     * @param number    数量
     * @return Object
     */
    @RequestMapping("add")
    public Object add(@LoginUser UserVo loginUser, @RequestParam Integer goodsId, @RequestParam Integer productId, @RequestParam Integer number) {

        //判断商品是否可以购买
        GoodsVo goodsInfo = goodsService.queryObject(goodsId);

        if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() != 1) {
            return this.toResponsFail("商品已下架");
        }

        //取得规格的信息,判断规格库存
        ProductVo productInfo = productService.queryObject(productId);
        if (null == productInfo || productInfo.getGoods_number() < number) {
            return this.toResponsFail("库存不足");
        }
        if (productInfo.getIs_on_sale() == 0) {
            return this.toResponsFail("产品已下架");
        }

        //判断购物车中是否存在此规格商品
        Map<String, Object> cartParam = new HashMap<>();
        cartParam.put("goods_id", goodsId);
        cartParam.put("product_id", productId);
        cartParam.put("user_id", loginUser.getUserId());
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == cartInfo) {

            cartInfo = new CartVo();

            cartInfo.setGoods_id(goodsId);
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setGoods_name(goodsInfo.getName());
            cartInfo.setProduct_name(productInfo.getProduct_name());
            cartInfo.setProduct_pic_url(productInfo.getPrimary_pic_url());
            cartInfo.setList_pic_url(goodsInfo.getPrimary_pic_url());
            cartInfo.setNumber(number);
            cartInfo.setSession_id("1");
            cartInfo.setUser_id(loginUser.getUserId());
            cartInfo.setRetail_price(productInfo.getRetail_price());
            cartInfo.setRetail_product_price(productInfo.getRetail_price());

            //todo 如果是会员，则以会员价为准
            if (loginUser.getIsMember() == 1) {
                cartInfo.setRetail_price(productInfo.getVipPrice());
                cartInfo.setRetail_product_price(productInfo.getVipPrice());
            }
            cartInfo.setMarket_price(productInfo.getMarket_price());
            cartInfo.setChecked(1);
            cartInfo.setProduct_status(1);
            cartService.save(cartInfo);
        } else {
            //如果已经存在购物车中，则数量增加
            if (productInfo.getGoods_number() < (number + cartInfo.getNumber())) {
                return this.toResponsFail("库存不足");
            }
            cartInfo.setNumber(cartInfo.getNumber() + number);
            cartService.update(cartInfo);
        }

        return toResponsSuccess(getCart(loginUser));
    }


    /**
     * 减少商品到购物车
     */
    @RequestMapping("minus")
    public Object minus(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        Integer goodsId = jsonParam.getInteger("goodsId");
        Integer productId = jsonParam.getInteger("productId");
        Integer number = jsonParam.getInteger("number");
        //判断购物车中是否存在此规格商品
        Map cartParam = new HashMap();
        cartParam.put("goods_id", goodsId);
        cartParam.put("product_id", productId);
        cartParam.put("user_id", loginUser.getUserId());
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo cartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        int cart_num = 0;
        if (null != cartInfo) {
            if (cartInfo.getNumber() > number) {
                cartInfo.setNumber(cartInfo.getNumber() - number);
                cartService.update(cartInfo);
                cart_num = cartInfo.getNumber();
            } else if (cartInfo.getNumber() == 1) {
                cartService.delete(cartInfo.getId());
                cart_num = 0;
            }
        }
        return toResponsSuccess(cart_num);
    }

    /**
     * 更新指定的购物车信息
     */
    @RequestMapping("update")
    public Object update(@LoginUser UserVo loginUser, Integer goodsId, Integer productId, Integer number, Integer id) {
        //参数判空
        if (Validator.isEmpty(goodsId)) {
            return this.toResponsFail("请提交goodsId");
        }
        if (Validator.isEmpty(productId)) {
            return this.toResponsFail("请提交productId");
        }
        if (Validator.isEmpty(number)) {
            return this.toResponsFail("请提交number");
        }
        if (Validator.isEmpty(id)) {
            return this.toResponsFail("请提交id");
        }
        //取得规格的信息,判断规格库存
        ProductVo productInfo = productService.queryObject(productId);
        if (null == productInfo || productInfo.getGoods_number() < number) {
//            return this.toResponsObject(1, "库存不足", "");
            return this.toResponsFail("库存不足");
        }
        //判断是否已经存在product_id购物车商品
        CartVo cartInfo = cartService.queryObject(id);
        //只是更新number
        if (cartInfo.getProduct_id().equals(productId)) {
            cartInfo.setNumber(number);
            cartService.update(cartInfo);
            return toResponsSuccess(getCart(loginUser));
        }

        Map<String, Object> cartParam = new HashMap<>();
        cartParam.put("goodsId", goodsId);
        cartParam.put("productId", productId);
        List<CartVo> cartInfoList = cartService.queryList(cartParam);
        CartVo newcartInfo = null != cartInfoList && cartInfoList.size() > 0 ? cartInfoList.get(0) : null;
        if (null == newcartInfo) {
            //添加操作
            //添加规格名和值
            String[] goodsSepcifitionValue = null;
            if (null != productInfo.getGoods_specification_ids()) {
                Map<String, Object> specificationParam = new HashMap<>();
                specificationParam.put("ids", productInfo.getGoods_specification_ids());
                specificationParam.put("goodsId", goodsId);
                List<GoodsSpecificationVo> specificationEntities = goodsSpecificationService.queryList(specificationParam);
                goodsSepcifitionValue = new String[specificationEntities.size()];
                for (int i = 0; i < specificationEntities.size(); i++) {
                    goodsSepcifitionValue[i] = specificationEntities.get(i).getValue();
                }
            }
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setNumber(number);
            cartInfo.setRetail_price(productInfo.getRetail_price());
            if (loginUser.getIsMember() == 1) {
                cartInfo.setRetail_price(productInfo.getVipPrice());
            }
            cartInfo.setMarket_price(productInfo.getRetail_price());
            if (null != goodsSepcifitionValue) {
                cartInfo.setGoods_specifition_name_value(StringUtils.join(goodsSepcifitionValue, ";"));
            }
            cartInfo.setGoods_specifition_ids(productInfo.getGoods_specification_ids());
            cartService.update(cartInfo);
        } else {
            //合并购物车已有的product信息，删除已有的数据
            Integer newNumber = number + newcartInfo.getNumber();
            if (null == productInfo || productInfo.getGoods_number() < newNumber) {
//                return this.toResponsObject(1, "库存不足", "");
                return this.toResponsFail("库存不足");
            }
            cartService.delete(newcartInfo.getId());
            //添加规格名和值
            String[] goodsSepcifitionValue = null;
            if (null != productInfo.getGoods_specification_ids()) {
                Map<String, Object> specificationParam = new HashMap<>();
                specificationParam.put("ids", productInfo.getGoods_specification_ids());
                specificationParam.put("goodsId", goodsId);
                List<GoodsSpecificationVo> specificationEntities = goodsSpecificationService.queryList(specificationParam);
                goodsSepcifitionValue = new String[specificationEntities.size()];
                for (int i = 0; i < specificationEntities.size(); i++) {
                    goodsSepcifitionValue[i] = specificationEntities.get(i).getValue();
                }
            }
            cartInfo.setProduct_id(productId);
            cartInfo.setGoods_sn(productInfo.getGoods_sn());
            cartInfo.setNumber(number);
            cartInfo.setRetail_price(productInfo.getRetail_price());
            if (loginUser.getIsMember() == 1) {
                cartInfo.setRetail_price(productInfo.getVipPrice());
            }
            cartInfo.setMarket_price(productInfo.getRetail_price());
            if (null != goodsSepcifitionValue) {
                cartInfo.setGoods_specifition_name_value(StringUtils.join(goodsSepcifitionValue, ";"));
            }
            cartInfo.setGoods_specifition_ids(productInfo.getGoods_specification_ids());
            cartService.update(cartInfo);
        }
        return toResponsSuccess(getCart(loginUser));
    }

    /**
     * 是否选择商品，如果已经选择，则取消选择，批量操作
     */
    @RequestMapping("checked")
    public Object checked(@LoginUser UserVo loginUser, String productIds, Integer isChecked) {

        if (Validator.isEmpty(productIds)) {
            return this.toResponsFail("请提交要取消选择的productIds，多个请用,隔开");
        }
        if (Validator.isEmpty(isChecked)) {
            return this.toResponsFail("请提交isChecked参数");
        }
        String[] productIdArray = productIds.split(",");
        cartService.updateCheck(productIdArray, isChecked, loginUser.getUserId());
        return toResponsSuccess(getCart(loginUser));
    }

    //删除选中的购物车商品，批量删除
    @RequestMapping("delete")
    public Object delete(@LoginUser UserVo loginUser, String productIds) {
        Long userId = loginUser.getUserId();

        if (Validator.isEmpty(productIds)) {
            return this.toResponsFail("请提交要删除的productIds，多个请用,隔开");
        }

        String[] productIdsArray = productIds.split(",");
        cartService.deleteByUserAndProductIds(userId, productIdsArray);

        return toResponsSuccess(getCart(loginUser));
    }

    //  获取购物车商品的总件件数
    @RequestMapping("goodscount")
    public Object goodscount(@LoginUser UserVo loginUser) {
        if (null == loginUser || null == loginUser.getUserId()) {
            return toResponsFail("未登录");
        }
        Map<String, Object> resultObj = new HashMap<>();
        //查询列表数据
        Map<String, Object> param = new HashMap<>();
        param.put("user_id", loginUser.getUserId());
        List<CartVo> cartList = cartService.queryList(param);
        //获取购物车统计信息
        Integer goodsCount = 0;
        for (CartVo cartItem : cartList) {
            goodsCount += cartItem.getNumber();
        }
        resultObj.put("cartList", cartList);
        //
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", goodsCount);
        //
        resultObj.put("cartTotal", cartTotal);
        return toResponsSuccess(resultObj);
    }

    /**
     * 订单提交前的检验和填写相关订单信息
     */
    @RequestMapping("checkout")
    public Object checkout(@LoginUser UserVo loginUser, Integer couponId) {
        Map<String, Object> resultObj = new HashMap<>();
        Long userId = loginUser.getUserId();
        //根据收货地址计算运费
        BigDecimal freightPrice = FREIGHT_PRICE;

        //采用通用字典中设置的运费
        SysMacroVo sysMacroVo = macroService.queryObject((long) 9);
        if (sysMacroVo != null) {
            String value = sysMacroVo.getValue();
            if (Validator.isNumber(value)) {
                freightPrice = new BigDecimal(value);
            }
        }

        //默认收货地址
        Map<String, Object> param = new HashMap<>();
        param.put("user_id", userId);

        List<AddressVo> addressEntities = addressService.queryList(param);
        AddressVo checkedAddress = null;
        if (addressEntities.size() > 0) {
            checkedAddress = addressEntities.get(0);
        }

        resultObj.put("checkedAddress", checkedAddress);

        //默认发票信息
        InvoiceVo checkedInvoice = apiInvoiceService.queryDefaultObject(userId);

        //设定默认值
        if (checkedInvoice == null) {
            checkedInvoice = new InvoiceVo();
            //发票类型：1-电子发票；2-纸质发票
            checkedInvoice.setInvoiceType(2);
            //抬头类型：1-个人；2-单位
            checkedInvoice.setHeaderType(1);
            //是否默认：0-否;1-是
            checkedInvoice.setIsDefault(1);
            //发票内容：1-商品明细；2-商品类别
            checkedInvoice.setContentType(1);
        }
        resultObj.put("checkedInvoice", checkedInvoice);

        //获取要购买的商品
        Map<String, Object> cartData = (Map<String, Object>) this.getCart(loginUser);

        List<CartVo> checkedGoodsList = new ArrayList<>();

        BigDecimal simpleGoodsTotalPrice = new BigDecimal(0.00);

        for (CartVo cartEntity : (List<CartVo>) cartData.get("cartList")) {
            //判断是否有产品已下架
            if (cartEntity.getProduct_status() == 0) {
                return toResponsFail(cartEntity.getProduct_name() + " 已失效");
            }

            if (cartEntity.getChecked() == 1) {
                checkedGoodsList.add(cartEntity);
            }

            //获取不是满减，不是折扣商品，不是第二份半价的商品的合计金额
            Integer goodsId = cartEntity.getGoods_id();
            GoodsVo goodsVo = goodsService.queryObject(goodsId);
            //是否满减1-是；0-否
            Integer isFullReduction = goodsVo.getIs_full_reduction();
            //是否折扣商品：1-是；0-否
            Integer isRebate = goodsVo.getIs_rebate();
            //是否第二份半价：1-是；0-否
            Integer isSecondHalfPrice = goodsVo.getIs_second_half_price();
            if (isFullReduction == 0 && isRebate == 0 && isSecondHalfPrice == 0) {
                simpleGoodsTotalPrice = simpleGoodsTotalPrice.add(cartEntity.getRetail_price().multiply(new BigDecimal(cartEntity.getNumber())));
            }

        }
        //计算订单的费用
        //商品总价
        BigDecimal goodsTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount");

        CouponVo couponVoInfo = null;
        BigDecimal couponPrice = new BigDecimal(0.00);
        BigDecimal fullCutCouponDec = new BigDecimal(0.00);
        //获取当前用户可用的优惠券信息
        if (couponId != null) {
            //todo 查询该优惠券的信息
            Map<String, Object> params = new HashMap<>();
            params.put("user_id", loginUser.getUserId());
            params.put("id", couponId);
            couponVoInfo = apiCouponService.queryObjectByUserId(params);
            if (couponVoInfo == null) {
                return toResponsFail("不存在该优惠券");
            }

            //todo 再查询有没有领取这个优惠券
            Map<String, Object> usercouponMap = new HashMap<>();
            usercouponMap.put("user_id", loginUser.getUserId());
            usercouponMap.put("coupon_id", couponId);
            int i = apiUserCouponService.queryTotal(usercouponMap);
            if (i == 0) {
                return toResponsFail("您没有领取该优惠券");
            }
            //todo 再查询是否在有效使用时间范围内
            boolean expired = DateUtil.isExpired(new Date(), DateField.SECOND, 0, couponVoInfo.getUse_end_date());
            if (expired) {
                return toResponsFail("该优惠券已经过期");
            }
            System.out.println("simpleGoodsTotalPrice:>>" + simpleGoodsTotalPrice);
            BigDecimal min_goods_amount = couponVoInfo.getMin_goods_amount();
            if (simpleGoodsTotalPrice.compareTo(min_goods_amount) < 0) {
                return toResponsFail("该优惠券不可用");
            }

            //使用优惠券减免的金额
            couponPrice = couponVoInfo.getType_money();
            //将满减金额设置为优惠券金额
            fullCutCouponDec = couponVoInfo.getType_money();

        }


        // 获取优惠信息提示
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("enabled", true);
        Integer[] send_types = new Integer[]{7};
        couponParam.put("send_types", send_types);
        List<CouponVo> couponVos = apiCouponService.queryList(couponParam);


        if (null != couponVos && couponVos.size() > 0) {
            for (CouponVo couponVo : couponVos) {
                // 判断是否免运费
                if (couponVo.getSend_type() == 7 && couponVo.getMin_goods_amount().compareTo(goodsTotalPrice) <= 0) {
                    freightPrice = new BigDecimal(0);
                }
            }
        }
        resultObj.put("fullCutCouponDec", fullCutCouponDec);

        //订单的总价
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);

        //减去其它支付的金额后，要实际支付的金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
        resultObj.put("freightPrice", freightPrice);
        //选用的优惠券
        resultObj.put("checkedCoupon", couponVoInfo);
        //当前用户可用的优惠券信息
//        resultObj.put("couponList", couponList);
        //优惠的价格
        resultObj.put("couponPrice", couponPrice);

        resultObj.put("checkedGoodsList", checkedGoodsList);
        resultObj.put("goodsTotalPrice", goodsTotalPrice);
        resultObj.put("orderTotalPrice", orderTotalPrice);
        resultObj.put("actualPrice", actualPrice);

        return toResponsSuccess(resultObj);
    }

    /**
     * 选择优惠券列表
     */
    @RequestMapping("checkedCouponList")
    public Object checkedCouponList(@LoginUser UserVo loginUser) {
        //
        Map<String, Object> param = new HashMap<>();
        param.put("user_id", loginUser.getUserId());
        List<CouponVo> couponVos = apiCouponService.queryUserCouponList(param);
        if (null != couponVos && couponVos.size() > 0) {
            // 获取要购买的商品
            Map<String, Object> cartData = (Map<String, Object>) this.getCart(loginUser);
            List<CartVo> checkedGoodsList = new ArrayList();
            List<Integer> checkedGoodsIds = new ArrayList();
            for (CartVo cartEntity : (List<CartVo>) cartData.get("cartList")) {
                if (cartEntity.getChecked() == 1) {
                    checkedGoodsList.add(cartEntity);
                    checkedGoodsIds.add(cartEntity.getId());
                }
            }
            //商品总价
            BigDecimal goodsTotalPrice = (BigDecimal) ((HashMap) cartData.get("cartTotal")).get("checkedGoodsAmount");

            // 如果没有用户优惠券直接返回新用户优惠券
//            for (CouponVo couponVo : couponVos) {
//                if (couponVo.getMin_goods_amount().compareTo(goodsTotalPrice) <= 0) {
//                }
//            }
        }
        return toResponsSuccess(couponVos);
    }
}
